import React from "react";
import {isLinux, isMac, isValidIp, isValidRule, isWindows, MessageType, msgTitleMap} from "../common/utils";
import {createFromIconfontCN} from "@ant-design/icons";
import path from "node:path";
import {IDefineModeOptions} from "react-codemirror2";
import {message} from "antd";
import remote = require("@electron/remote")

export function showMessage(msg: string, type: MessageType) {
    if (remote.getCurrentWindow().isVisible()) {
        message[type](msg)
    } else {
        new Notification(msgTitleMap[type], {body: msg});
    }
}

export function showSuccessMsg(msg: string) {
    showMessage(msg, MessageType.success)
}

export function showErrorMsg(msg: string) {
    showMessage(msg, MessageType.error)
}

export const IconFont = createFromIconfontCN({
    scriptUrl: `file://${path.resolve(__dirname, "../iconfont/iconfont.js")}`
})

export function LogoIcon() {
    return <IconFont type="logo"/>;
}

export function SystemIcon() {
    if (isWindows()) {
        return <IconFont type="windows"/>;
    }
    if (isLinux()) {
        return <IconFont type="linux"/>;
    }
    if (isMac()) {
        return <IconFont type="mac"/>;
    }
    return <IconFont type="logo"/>;
}

export const hostsMode: IDefineModeOptions = {
    name: "hosts",
    fn: () => {
        return {
            token: (stream, state) => {
                const ch = stream.next();
                if (ch === "#") {
                    stream.skipToEnd();
                    return "comment";
                }

                if (!stream.string.trim()) {
                    return null;
                }
                if (!isValidRule(stream.string.trim())) {
                    return "error-rules"
                }
                const matchIp = stream.match(/^([0-9a-f:.]+)[ \r\t]+/);
                if (matchIp && stream.pos <= `${ch}${matchIp[0]}`.length) {
                    if (!isValidIp(matchIp[1].trim())) return "error-rules";
                    return "number"
                }
                return "variable";
            }
        };
    }
}